import { t } from '@/components/utils';
import {
  applyTheme,
  getSavedTheme,
  getThemeStyleInfo,
  themeStyles,
  type ThemeKey,
  type ThemeStyle,
} from '@/config/themeConfig';
import { BgColorsOutlined } from '@ant-design/icons';
import { Button, Dropdown, Typography } from 'antd';
import React, { useEffect, useState } from 'react';
import './index.less';

const { Text } = Typography;

/**
 * 主题切换组件
 */
const ThemeToggle: React.FC<{
  onChange?: (themeKey: ThemeKey) => void;
}> = ({ onChange }) => {
  // 从 localStorage 读取保存的主题，如果没有则使用默认主题
  const getInitialTheme = (): ThemeKey => {
    try {
      const saved = getSavedTheme();
      return saved || 'blue-light';
    } catch {
      return 'blue-light';
    }
  };

  const [currentTheme, setCurrentTheme] = useState<ThemeKey>(getInitialTheme);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);

  // 确保主题被正确应用
  useEffect(() => {
    applyTheme(currentTheme);
  }, [currentTheme]);

  // 主题切换处理
  const handleThemeChange = (themeKey: ThemeKey) => {
    setCurrentTheme(themeKey);
    applyTheme(themeKey);
    setIsDropdownOpen(false);
    onChange?.(themeKey);
  };

  // 渲染主题选择面板
  const renderThemePanel = () => {
    const { style: currentStyle } = getThemeStyleInfo(currentTheme);

    return (
      <div className="theme-panel">
        <div className="theme-panel-content">
          <div className="theme-options-container">
            {Object.entries(themeStyles).map(([styleKey, info]) => {
              const isSelected = styleKey === currentStyle;
              const themeKey: ThemeKey = `${styleKey as ThemeStyle}-light`;

              return (
                <Button
                  key={styleKey}
                  block
                  size="small"
                  type={isSelected ? 'primary' : 'default'}
                  onClick={() => handleThemeChange(themeKey)}
                  className="theme-option-button"
                >
                  <div className="theme-icon">{info.icon}</div>
                  <Text className="theme-text">{t('common', `${styleKey}ThemeName`)}</Text>
                </Button>
              );
            })}
          </div>
        </div>
      </div>
    );
  };

  const { info: currentThemeInfo } = getThemeStyleInfo(currentTheme);

  return (
    <Dropdown
      open={isDropdownOpen}
      onOpenChange={setIsDropdownOpen}
      trigger={['hover']}
      popupRender={() => renderThemePanel()}
      placement="bottomRight"
      overlayStyle={{
        paddingTop: '8px',
        border: 'none',
        background: 'transparent',
        boxShadow: 'none',
      }}
      overlayClassName="theme-dropdown-overlay"
    >
      <Button type="text" icon={<BgColorsOutlined />} className="theme-toggle-button">
        <span className="current-theme-icon">{currentThemeInfo.icon}</span>
      </Button>
    </Dropdown>
  );
};

export default ThemeToggle;
